<?php
header("Content-type: text/html; charset=utf-8");
ini_set('display_errors', 1);
set_time_limit(0);
include_once dirname(dirname(__FILE__)) . '/mgtv_init.php';
include_once dirname(dirname(dirname(__FILE__))) . '/nn_logic/notify_message/notify_message.class.php';
include_once dirname(dirname(dirname(dirname(__FILE__)))) . '/np/np_http_curl.class.php';

class async_notify_message extends nn_timer
{
	//反馈条数
	public $notify_num = 20;
	
	public function action($params = null)
	{
		$this->msg('开始执行...');
		$this->do_timer_action();
		$this->msg('执行结束...');
	}
	/**
	 * 脚本执行体
	 * @author zhiyong.luo
	 */
	private function do_timer_action()
	{
		$dc = nl_get_dc(array (
				"db_policy" => NL_DB_WRITE | NL_DB_READ,
				"cache_policy" => NP_KV_CACHE_TYPE_MEMCACHE
		));
		$dc->open();
		$sp_all = nl_sp::query_all($dc);
		$sp_info = array();
		if($sp_all['ret'] == 0 && !empty($sp_all['data_info']) && is_array($sp_all['data_info']))
		{
			$sp_info = $sp_all['data_info'];
		}
		if (!is_array($sp_info))
		{
			echo "SP未配置\r\n";
			return ;
		}
		foreach ($sp_info as $sp_list)
		{
			$sp_config = isset($sp_list['nns_config']) && !empty($sp_list['nns_config']) ? json_decode($sp_list['nns_config'], true) : null;
			if (!isset($sp_config['site_callback_url']) && strlen($sp_config['site_callback_url']) <= 0)
			{
				echo "SP:" . $sp_list['nns_id'] . "没有配置反馈地址\r\n";
				continue;
			}
			//获取SP的反馈消息
			$params = array(
					'nns_status' => 0,
					'nns_org_id' => $sp_list['nns_id'],
			);
			$notify_re = nl_notify_message::get_nofity_message($dc,$params,0,$this->notify_num);
			if($notify_re['ret'] != 0)
			{
				echo "不存在反馈的消息\r\n";
				return ;
			}
			if(empty($notify_re['data_info']))
			{
				echo "不存在反馈的消息\r\n";
				return ;
			}
			foreach ($notify_re['data_info'] as $notify)
			{
				$result = $this->curl_post($sp_config['site_callback_url'],$notify['nns_notify']);
				if($result)
				{
					nl_notify_message::modify_notify_message($dc,array('nns_status' => 3),array('nns_id' => $notify['nns_id']));
				}
			}
		}
	}
	/**
	 * 异步回调
	 * @param unknown $url
	 * @param unknown $content
	 */
	private function curl_post($url,$content)
	{
		$http_curl = new np_http_curl_class();
		$http_header = array("Content-Type: text/xml");
		$response = $http_curl->post($url,$content,$http_header,5);
		$curl_info = $http_curl->curl_getinfo();
		$http_code = $curl_info['http_code'];
		if($http_code == 200)
		{
			return true;
		}
		return false;
	}
}
$async_notify_message = new async_notify_message("async_notify_message", 'public',__FILE__);
$async_notify_message->run();